package com.emapp.lccode.activity

import android.content.Context
import android.os.Bundle
import androidx.lifecycle.viewModelScope
import com.emapp.lccode.R
import com.emapp.lccode.adapter.ProgressImageAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.databinding.ActivityProgressInfoBinding
import com.emapp.lccode.mode.ProjectDeviceViewModel
import com.emapp.lccode.utils.DividerOrientation
import com.emapp.lccode.utils.GlideEngine
import com.emapp.lccode.utils.divider
import com.emapp.lccode.utils.downloadAndSaveImage
import com.emapp.lccode.utils.getColorExt
import com.emapp.lccode.utils.grid
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.emapp.lccode.utils.showMessage
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.Toaster
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.style.PictureSelectorStyle
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 进度详情
 */
class ProgressInfoActivity : BaseActivity1<ProjectDeviceViewModel, ActivityProgressInfoBinding>() {
    private val imageAdapter: ProgressImageAdapter by lazy { ProgressImageAdapter() }
    var images: ArrayList<LocalMedia> = arrayListOf()
    private val imageAdapter2: ProgressImageAdapter by lazy { ProgressImageAdapter() }
    var images2: ArrayList<LocalMedia> = arrayListOf()
    lateinit var id: String
    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        id = intent.getStringExtra("id").toString()
        mViewBind.lvTitle.tvTitle.text = "进度详情"
        EventBus.getDefault().register(this)
        mViewBind.rvList.run {
            grid(4)
            adapter = imageAdapter
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter.setOnItemClickListener { adapter, _, position ->
            PictureSelector.create(this)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .setSelectorUIStyle(PictureSelectorStyle())
                .isPreviewFullScreenMode(true)
                .isHidePreviewDownload(false)
                .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                    override fun onLongPressDownload(
                        context: Context?,
                        media: LocalMedia
                    ): Boolean {
                        XXPermissions.with(this@ProgressInfoActivity) // 不适配 Android 11 可以这样写
                            .permission(Permission.MANAGE_EXTERNAL_STORAGE) // .permission(Permission.CAMERA)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(permissions: List<String>, all: Boolean) {
                                    mViewModel.viewModelScope.launch {
                                        downloadAndSaveImage(this@ProgressInfoActivity,media.availablePath)
                                    }
                                    log_e("media--" + media.availablePath)
                                }

                                override fun onDenied(permissions: List<String>, never: Boolean) {}
                            })

                        return true
                    }

                    override fun onPreviewDelete(position: Int) {
                    }
                })
                .startActivityPreview(position, false, images)

        }



        mViewBind.rvList2.run {
            grid(4)
            adapter = imageAdapter2
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter2.setOnItemClickListener { adapter, _, position ->
            PictureSelector.create(this)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .setSelectorUIStyle(PictureSelectorStyle())
                .isPreviewFullScreenMode(true)
                .isHidePreviewDownload(false)
                .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                    override fun onLongPressDownload(
                        context: Context?,
                        media: LocalMedia
                    ): Boolean {
                        XXPermissions.with(this@ProgressInfoActivity) // 不适配 Android 11 可以这样写
                            .permission(Permission.MANAGE_EXTERNAL_STORAGE) // .permission(Permission.CAMERA)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(permissions: List<String>, all: Boolean) {
                                    mViewModel.viewModelScope.launch {
                                        downloadAndSaveImage(this@ProgressInfoActivity,media.availablePath)
                                    }
                                    log_e("media--" + media.availablePath)
                                }

                                override fun onDenied(permissions: List<String>, never: Boolean) {}
                            })

                        return true
                    }

                    override fun onPreviewDelete(position: Int) {
                    }
                })
                .startActivityPreview(position, false, images2)

        }
        mViewModel.getProgressInfor(id)
    }

    override fun createObserver() {
        mViewModel.run {
            device.observe(this@ProgressInfoActivity) { resultState ->
                parseState(resultState, {
                    if (it.isNotEmpty())
                        setInfo(it[0])
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
        }
    }

    fun setInfo(info: DeviceKt) {
        mViewBind.run {
            tvWell.text = info.welllname
            tvDate.text = info.date_time
            tvUsername.text = info.username
            tvCompany.text = info.department_name
            tvGongxu.text = info.name
            tvContent.text = info.content
            tvRemark.text = info.remark
        }
        if (info.fileArray != null) {
            images.clear()
            info.fileArray.forEach {
                val l = LocalMedia()
                l.path = BaseConfig.ROOT_URL + it.filepath
                images.add(l)
            }
            imageAdapter.submitList(info.fileArray)
        }
        if (info.materialsfileArray != null) {
            images2.clear()
            info.materialsfileArray.forEach {
                val l = LocalMedia()
                l.path = BaseConfig.ROOT_URL + it.filepath
                images2.add(l)
            }
            imageAdapter2.submitList(info.materialsfileArray)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.lvTitle.tvRight
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.PROJECT_DEVICE -> {
                // infor=event.`object` as DeviceKt
            }

            else -> {}
        }
    }

}
